﻿(function () {
    var doc = document,
        nav = navigator,
        dm = doc.documentMode,
        ua = nav.userAgent,
        pf = nav.platform,
        p = doc.URL.split('?')[0],
    /*  server = '{{Server}}',*/
        un = '{{UserName}}',
        spath = '{{ServerPath}}',
        ur = '{{UserRole}}',
        manuallyLog = '{{ManuallyLog}}',
        siteid = '{{SiteId}}',
        cName = 'tongji.fz',
        loged = 0,
        ref = (doc.referrer || '').split('?')[0];

    function GetCookie() {
        var arr = document.cookie.split('; ');
        for (var i = 0, len = arr.length; i < len; i++) {
            if (~arr[i].indexOf(cName + '=')) {
                return arr[i].split(cName + '=')[1];
            }
        }
    }
    function setCookie(val) {
        var d = new Date();
        d.setFullYear(2100);
        document.cookie = cName + '=' + val + ';expire=' + d.toUTCString() + ';path=' + spath;
    }

    function getSign() {
        var d = new Date();
        return "tongji-" + siteid + '-' + d.getFullYear() + (d.getMonth() + 1) + d.getDate() + '-' + d.getTime();
    }

    function getServerPath() {
        var arr = doc.getElementsByTagName('script'), t, j;
        for (var i = 0, len = arr.length; i < len; i++) {
            t = arr[i].src || arr[i].getAttribute('src');
            if (t) {
                t = t.toString().toLowerCase();
                j = t.indexOf('tongji.ashx');
                if (~j) {
                    return t.substring(0, j);
                }
            }
        }
    }

    function fEncode(v) {
        return encodeURIComponent(v);
    }

    function log() {
        if (loged) {
            return 0;
        }
        var server = getServerPath();
        var u = GetCookie();
        if (!u) {
            u = getSign();
            setCookie(u);
        }
        var loc = 'log.ashx?siteid=' + siteid + '&us=' + u + '&ua=' + fEncode(ua) + '&swh=' + screen.width + 'x' + screen.height + '&pf=' + pf +
            '&bwh=' + doc.documentElement.clientWidth + 'x' + doc.documentElement.clientHeight;
        dm && (loc += '&dm=' + dm);
        un && (loc += '&un=' + fEncode(un));
        ur && (loc += '&ur=' + fEncode(ur));
        ref && (loc += '&rf=' + fEncode(ref));
        !nav.cookieEnabled && (loc += '&sck=0');
        (new Image).src = server + loc + '&t=' + Math.random();
        loged = 1;
        return 1;
    }

    try {
        !manuallyLog && log();
        window.TongJi = { log: log };
    } catch (e) {
        console && console.error(e);
    }
})();